package com.crack.spansframe;

import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.text.Layout;
import android.text.Spannable;
import android.text.style.LeadingMarginSpan;
import android.text.style.LineBackgroundSpan;
import android.widget.TextView;

import com.crack.spansframe.extra.INeedTextView;

/**
 * 参照{@link SpanSolve#SpanSolve(String)}
 * 如果不需要此处理，请将{@link MarginQuoteSpan#LINE_OFFSET}置为0
 * Created by liuyu on 16-4-19.
 */
public class MarginQuoteSpan implements LineBackgroundSpan, INeedTextView, LeadingMarginSpan {

    public static int DEFAULT_QUOTE_MARGIN = 30;

    TextView textView;

    /**
     * 为了美观，在被引用文本的前后各增加一个换行符，前提是文本本身经过相应的处理
     * 参照{@link SpanSolve#SpanSolve(String)}
     */
    public static int LINE_OFFSET = 1;

    @Override
    public void drawBackground(Canvas c, Paint p, int left, int right, int top, int baseline
            , int bottom, CharSequence text, int start, int end, int lnum) {
        Spannable spannable = (Spannable) text;
        if (spannable.getSpanStart(this) == start) {
            start = spannable.getSpanStart(this);
            end = spannable.getSpanEnd(this);
            Rect rect = new Rect();
            Drawable drawable = SpanSolve.sQuoteDrawable;
            Layout layout = textView.getLayout();
            int lineStart = layout.getLineForOffset(start);
            int lineEnd = layout.getLineForOffset(end);
            rect.set(left, layout.getLineTop(lineStart - LINE_OFFSET), right, layout.getLineBottom(lineEnd + LINE_OFFSET));
            drawable.setBounds(rect);
            drawable.draw(c);
        }
//            int old = p.getColor();
//            Paint.Style style = p.getStyle();
//            c.save();
//            p.setStyle(Paint.Style.FILL);
//            p.setColor(Color.parseColor("#f2eddf"));
//            c.drawRect(left, top, right, bottom, p);
//            c.restore();
//            p.setColor(old);
//            p.setStyle(style);
    }

    @Override
    public void setTextView(TextView textView) {
        this.textView = textView;
    }

    @Override
    public int getLeadingMargin(boolean first) {
        return DEFAULT_QUOTE_MARGIN;
    }

    @Override
    public void drawLeadingMargin(Canvas c, Paint p, int x, int dir, int top, int baseline, int bottom, CharSequence text, int start, int end, boolean first, Layout layout) {

    }
}
